﻿using System;
using System.Collections.Generic;
using System.Text;
using NHibernate;
using System.BusinessObjects.Transactions;
using Blazing.BusinessObjects.Locations;
using Blazing.BusinessObjects.Tagging;
using NHibernate.Criterion;
using System.BusinessObjects.With;
using System.Collections;

namespace Blazing.BusinessObjects.Queries
{
    /// <summary>
    /// Searches and returns a list of assets which are associated with one or more 
    /// of the provided taxonomytags
    /// </summary>
    public class QrySearchAssetsByTaxonomyTags
    {
        /// <summary>
        /// Returns assets based on tags
        /// </summary>
        public static IQuery Query(IList<TaxonomyTag> tags)
        {
            return Query(tags, -1);
        }

        /// <summary>
        /// Returns assets, filters based on tags and an assetTypeID
        /// </summary>
        public static IQuery Query(IList<TaxonomyTag> tags, int assetTypeID)
        {            
            string hql = "select a1 from Asset a1{0}{1}";
            string tables = "";
            string wherelist = "";

            // If we have tags, we'll have some where clauses
            if (tags.Count > 0)
                wherelist = " where ";

            // Limit based on the assetTypeID if available
            if (assetTypeID > -1)
                wherelist += string.Format("a1.AssetType.ID = {0}", assetTypeID);

            // Build the query as an inner join between the assets
            // and the limited set of assettaxonomytags
            for (int i = 0; i < tags.Count; i++)
            {
                tables += string.Format(" join a1.TaxonomyTags att{0}", i);
                if (wherelist.Length > 6)
                    wherelist += string.Format(" and");
                wherelist += string.Format(" att{0}.ID = :tid{0}", i);
            }

            IQuery qry = UnitOfWork.CurrentSession.CreateQuery(string.Format(hql, tables, wherelist));

            // Add the tag values as parameters
            for (int i = 0; i < tags.Count; i++)
            {
                qry.SetParameter("tid" + i, tags[i]);
            }

            qry.SetCacheable(true);
            return qry;
        } 
    }
}
